﻿using System;

namespace DAPNet
{
    public class KasparisLaneCorrector : IClickCorrector
    {
        private MedianFilter medianFilter;


        public KasparisLaneCorrector()
        {
            this.medianFilter = new MedianFilter(0);
        }

        public void Correct(SampleCollection samples, ClickDetection detection)
        {
            int[] g = GetGatingSignal(detection);
            for (int i = 0; i < samples.Count; i++)
            {
                if (g[i] != 0)
                {
                    medianFilter.Parameter = g[i];
                    double medianValue = medianFilter.GetMedianValueAt(samples, i);
                    samples[i].SetTrimmedValue(medianValue);  
                }
            }
        }

        private int[] GetGatingSignal(ClickDetection detection)
        {
            int[] gatingSignal = new int[detection.Count];
            int numConsecutives = 0;
            for (int i = 0; i < detection.Count; i++)
            {
                if (detection[i])
                {
                    numConsecutives++;
                }
                else if (numConsecutives > 0)
                {
                    for (int j = i - numConsecutives; j < i; j++)
                    {
                        gatingSignal[j] = numConsecutives;
                    }
                    numConsecutives = 0;    
                }
            }
            return gatingSignal;
        }
    }
}
